package com.example.smartcommunity.com.example.utils;

import com.google.gson.Gson;

import java.io.IOException;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OkHttpUtils {

    private static final String ip = "192.168.43.200:8181";
    private static final String temp = "/zhsq/";

    public static void getDataFromIntent(final String path, final Map<String, Object> map, final CallBack callBack) {
        final String uri = "https://" + ip + temp + path;
        new Thread(new Runnable() {
            @Override
            public void run() {
                sendOkHttpRequest(map, uri, callBack);
            }

            private void sendOkHttpRequest(Map<String, Object> map, String uri, final CallBack callBack) {
                MediaType Json = MediaType.parse("application/json;charset=utf-8");
                Gson gson = new Gson();
                String json = gson.toJson(map);
                OkHttpClient okHttpClient = new OkHttpClient();
                RequestBody body = RequestBody.create(Json, json);
                final Request request = new Request.Builder().url(uri).get().build();
                okHttpClient.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        callBack.onErrer(e);
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        if (response.isSuccessful()) {
//                            Log.i(TAG, "onResponse: requsert success");
                            String body = response.body().string();
                            callBack.successful(body);
//                            callBack.successful(body);
                        }
                    }
                });
            }
        }).start();
    }

    public interface CallBack {
        void successful(String string);
        void onErrer(Exception e);
    }

}